from communication.asyncClient import AsyncClient
from public.convert import convert
from robot.comm.pluginBase import Session
from robot.comm.command import NormalCommand, RegexCommand


async def translate(from_: str, to_: str, text: str) -> str:
    async with AsyncClient('translate') as client:
        return await client.send({
            'from': from_,
            'to': to_,
            'text': convert('internal', 'plain', text),
        })


@RegexCommand(r'(.*?)[语文]?译(.*?)[语文]? (.*)')
async def translate_from_to(session: Session, from_: str, to_: str, text: str) -> None:
    result = await translate(from_, to_, text)
    await session.reply(result)


@RegexCommand(r'(.*)用(.*?)[语文]?怎么说[?？]?$')
async def translate_to(session: Session, text: str, to_: str) -> None:
    result = await translate('auto', to_, text)
    await session.reply(result)


@NormalCommand('翻译')
@RegexCommand(r'(.*)是什么意思[?？]?$')
async def translate_auto(session: Session, text: str) -> None:
    result = await translate('auto', 'zh', text)
    if result == text:
        result = await translate('auto', 'en', text)
    await session.reply(result)
